import { zodResolver } from "@hookform/resolvers/zod";
import { Button } from "@poketto/ui/button";
import { Calendar } from "@poketto/ui/calendar";
import { Checkbox } from "@poketto/ui/checkbox";
import {
	Command,
	CommandEmpty,
	CommandGroup,
	CommandInput,
	CommandItem,
	CommandList,
} from "@poketto/ui/command";
import {
	Form,
	FormControl,
	FormDescription,
	FormField,
	FormItem,
	FormLabel,
	FormMessage,
} from "@poketto/ui/form";
import { useToast } from "@poketto/ui/hooks/use-toast";
import { Input } from "@poketto/ui/input";
import { Popover, PopoverContent, PopoverTrigger } from "@poketto/ui/popover";
import { RadioGroup, RadioGroupItem } from "@poketto/ui/radio-group";
import {
	Select,
	SelectContent,
	SelectItem,
	SelectTrigger,
	SelectValue,
} from "@poketto/ui/select";
import { Switch } from "@poketto/ui/switch";
import { Textarea } from "@poketto/ui/textarea";
import { CalendarIcon, CaretSortIcon, CheckIcon } from "@radix-ui/react-icons";
import { format } from "date-fns";
import { useForm } from "react-hook-form";
import { Link } from "react-router";
import { z } from "zod";

import { cn } from "@/lib/utils";

const languages = [
	{ label: "English", value: "en" },
	{ label: "French", value: "fr" },
	{ label: "German", value: "de" },
	{ label: "Spanish", value: "es" },
	{ label: "Portuguese", value: "pt" },
	{ label: "Russian", value: "ru" },
	{ label: "Japanese", value: "ja" },
	{ label: "Korean", value: "ko" },
	{ label: "Chinese", value: "zh" },
] as const;
const items = [
	{
		id: "recents",
		label: "Recents",
	},
	{
		id: "home",
		label: "Home",
	},
	{
		id: "applications",
		label: "Applications",
	},
	{
		id: "desktop",
		label: "Desktop",
	},
	{
		id: "downloads",
		label: "Downloads",
	},
	{
		id: "documents",
		label: "Documents",
	},
] as const;

const formSchema = z.object({
	username: z.string().min(2).max(50),
	items: z.array(z.string()).refine((value) => value.some(Boolean), {
		message: "You have to select at least one item.",
	}),
	dob: z.date({
		required_error: "A date of birth is required.",
	}),
	type: z.enum(["all", "mentions", "none"], {
		required_error: "You need to select a notification type.",
	}),
	email: z
		.string({
			required_error: "Please select an email to display.",
		})
		.email(),
	marketing_emails: z.boolean().default(false).optional(),
	security_emails: z.boolean(),
	bio: z
		.string()
		.min(10, {
			message: "Bio must be at least 10 characters.",
		})
		.max(160, {
			message: "Bio must not be longer than 30 characters.",
		}),
	language: z.string({
		required_error: "Please select a language.",
	}),
});
export default function Component() {
	const { toast } = useToast();

	// 1. Define your form.
	const form = useForm<z.infer<typeof formSchema>>({
		resolver: zodResolver(formSchema),
		defaultValues: {
			username: "",
			items: ["recents", "home"],
		},
	});

	// 2. Define a submit handler.
	function onSubmit(values: z.infer<typeof formSchema>) {
		// Do something with the form values.
		// ✅ This will be type-safe and validated.

		toast({
			title: "You submitted the following values:",
			description: (
				<pre className="mt-2 w-[340px] rounded-md bg-slate-950 p-4">
					<code className="text-white">{JSON.stringify(values, null, 2)}</code>
				</pre>
			),
		});
	}
	return (
		<div className="mx-auto max-w-3xl p-6">
			<div className="mb-8">
				<h1 className="text-2xl font-bold tracking-tight">Basic Form</h1>
				<p className="text-muted-foreground">
					Fill out the form below with your information.
				</p>
			</div>

			<Form {...form}>
				<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-8">
					{/* Personal Information Group */}
					<div className="rounded-lg border p-6">
						<h2 className="mb-6 text-lg font-medium">Personal Information</h2>
						<div className="space-y-6">
							<FormField
								control={form.control}
								name="username"
								render={({ field }) => (
									<FormItem>
										<FormLabel>Username</FormLabel>
										<FormControl>
											<Input placeholder="shadcn" {...field} />
										</FormControl>
										<FormDescription>
											This is your public display name.
										</FormDescription>
										<FormMessage />
									</FormItem>
								)}
							/>

							<div className="grid gap-6 sm:grid-cols-2">
								<FormField
									control={form.control}
									name="dob"
									render={({ field }) => (
										<FormItem className="flex flex-col">
											<FormLabel>Date of birth</FormLabel>
											<Popover>
												<PopoverTrigger asChild>
													<FormControl>
														<Button
															variant="outline"
															className={cn(
																"w-[240px] pl-3 text-left font-normal",
																!field.value && "text-muted-foreground",
															)}
														>
															{field.value ? (
																format(field.value, "PPP")
															) : (
																<span>Pick a date</span>
															)}
															<CalendarIcon className="ml-auto size-4 opacity-50" />
														</Button>
													</FormControl>
												</PopoverTrigger>
												<PopoverContent className="w-auto p-0" align="start">
													<Calendar
														mode="single"
														selected={field.value}
														onSelect={field.onChange}
														disabled={(date) =>
															date > new Date() || date < new Date("1900-01-01")
														}
														initialFocus
													/>
												</PopoverContent>
											</Popover>
											<FormDescription>
												Your date of birth is used to calculate your age.
											</FormDescription>
											<FormMessage />
										</FormItem>
									)}
								/>

								<FormField
									control={form.control}
									name="language"
									render={({ field }) => (
										<FormItem className="flex flex-col">
											<FormLabel>Language</FormLabel>
											<Popover>
												<PopoverTrigger asChild>
													<FormControl>
														<Button
															variant="outline"
															type="button"
															className={cn(
																"w-[200px] justify-between",
																!field.value && "text-muted-foreground",
															)}
														>
															{field.value
																? languages.find(
																		(language) =>
																			language.value === field.value,
																	)?.label
																: "Select language"}
															<CaretSortIcon className="ml-2 size-4 shrink-0 opacity-50" />
														</Button>
													</FormControl>
												</PopoverTrigger>
												<PopoverContent className="w-[200px] p-0">
													<Command>
														<CommandInput
															placeholder="Search framework..."
															className="h-9"
														/>
														<CommandList>
															<CommandEmpty>No framework found.</CommandEmpty>
															<CommandGroup>
																{languages.map((language) => (
																	<CommandItem
																		value={language.label}
																		key={language.value}
																		onSelect={() => {
																			form.setValue("language", language.value);
																		}}
																	>
																		{language.label}
																		<CheckIcon
																			className={cn(
																				"ml-auto size-4",
																				language.value === field.value
																					? "opacity-100"
																					: "opacity-0",
																			)}
																		/>
																	</CommandItem>
																))}
															</CommandGroup>
														</CommandList>
													</Command>
												</PopoverContent>
											</Popover>
											<FormDescription>
												This is the language that will be used in the dashboard.
											</FormDescription>
											<FormMessage />
										</FormItem>
									)}
								/>
							</div>

							<FormField
								control={form.control}
								name="bio"
								render={({ field }) => (
									<FormItem>
										<FormLabel>Bio</FormLabel>
										<FormControl>
											<Textarea
												placeholder="Tell us a little bit about yourself"
												className="resize-none"
												{...field}
											/>
										</FormControl>
										<FormDescription>
											You can <span>@mention</span> other users and
											organizations.
										</FormDescription>
										<FormMessage />
									</FormItem>
								)}
							/>
						</div>
					</div>

					{/* Contact & Notifications Group */}
					<div className="rounded-lg border p-6">
						<h2 className="mb-6 text-lg font-medium">
							Contact & Notifications
						</h2>
						<div className="space-y-6">
							<FormField
								control={form.control}
								name="email"
								render={({ field }) => (
									<FormItem>
										<FormLabel>Email</FormLabel>
										<Select
											onValueChange={field.onChange}
											defaultValue={field.value}
										>
											<FormControl>
												<SelectTrigger>
													<SelectValue placeholder="Select a verified email to display" />
												</SelectTrigger>
											</FormControl>
											<SelectContent>
												<SelectItem value="m@example.com">
													m@example.com
												</SelectItem>
												<SelectItem value="m@google.com">
													m@google.com
												</SelectItem>
												<SelectItem value="m@support.com">
													m@support.com
												</SelectItem>
											</SelectContent>
										</Select>
										<FormDescription>
											You can manage email addresses in your{" "}
											<Link to="/examples/forms">email settings</Link>.
										</FormDescription>
										<FormMessage />
									</FormItem>
								)}
							/>

							<FormField
								control={form.control}
								name="type"
								render={({ field }) => (
									<FormItem className="space-y-3">
										<FormLabel>Notify me about...</FormLabel>
										<FormControl>
											<RadioGroup
												onValueChange={field.onChange}
												defaultValue={field.value}
												className="flex flex-col space-y-1"
											>
												<FormItem className="flex items-center space-x-3 space-y-0">
													<FormControl>
														<RadioGroupItem value="all" />
													</FormControl>
													<FormLabel className="font-normal">
														All new messages
													</FormLabel>
												</FormItem>
												<FormItem className="flex items-center space-x-3 space-y-0">
													<FormControl>
														<RadioGroupItem value="mentions" />
													</FormControl>
													<FormLabel className="font-normal">
														Direct messages and mentions
													</FormLabel>
												</FormItem>
												<FormItem className="flex items-center space-x-3 space-y-0">
													<FormControl>
														<RadioGroupItem value="none" />
													</FormControl>
													<FormLabel className="font-normal">Nothing</FormLabel>
												</FormItem>
											</RadioGroup>
										</FormControl>
										<FormMessage />
									</FormItem>
								)}
							/>

							<div className="space-y-4">
								<h3 className="font-medium">Email Notifications</h3>
								<div className="space-y-4">
									<FormField
										control={form.control}
										name="marketing_emails"
										render={({ field }) => (
											<FormItem className="flex flex-row items-center justify-between rounded-lg border p-4 shadow-sm">
												<div className="space-y-0.5">
													<FormLabel>Marketing emails</FormLabel>
													<FormDescription>
														Receive emails about new products, features, and
														more.
													</FormDescription>
												</div>
												<FormControl>
													<Switch
														checked={field.value}
														onCheckedChange={field.onChange}
													/>
												</FormControl>
											</FormItem>
										)}
									/>
									<FormField
										control={form.control}
										name="security_emails"
										render={({ field }) => (
											<FormItem className="flex flex-row items-center justify-between rounded-lg border p-4 shadow-sm">
												<div className="space-y-0.5">
													<FormLabel>Security emails</FormLabel>
													<FormDescription>
														Receive emails about your account security.
													</FormDescription>
												</div>
												<FormControl>
													<Switch
														checked={field.value}
														onCheckedChange={field.onChange}
														disabled
														aria-readonly
													/>
												</FormControl>
											</FormItem>
										)}
									/>
								</div>
							</div>
						</div>
					</div>

					{/* Sidebar Items Group */}
					<div className="rounded-lg border p-6">
						<h2 className="mb-6 text-lg font-medium">Sidebar Preferences</h2>
						<FormField
							control={form.control}
							name="items"
							render={() => (
								<FormItem>
									<div className="mb-4">
										<FormLabel className="text-base">Sidebar</FormLabel>
										<FormDescription>
											Select the items you want to display in the sidebar.
										</FormDescription>
									</div>
									{items.map((item) => (
										<FormField
											key={item.id}
											control={form.control}
											name="items"
											render={({ field }) => (
												<FormItem
													key={item.id}
													className="flex flex-row items-start space-x-3 space-y-0"
												>
													<FormControl>
														<Checkbox
															checked={field.value?.includes(item.id)}
															onCheckedChange={(checked) =>
																checked
																	? field.onChange([...field.value, item.id])
																	: field.onChange(
																			field.value?.filter(
																				(value) => value !== item.id,
																			),
																		)
															}
														/>
													</FormControl>
													<FormLabel className="text-sm font-normal">
														{item.label}
													</FormLabel>
												</FormItem>
											)}
										/>
									))}
									<FormMessage />
								</FormItem>
							)}
						/>
					</div>

					<div className="flex justify-end">
						<Button type="submit" size="lg">
							Save Changes
						</Button>
					</div>
				</form>
			</Form>
		</div>
	);
}
